const express = require("express");
const fs = require("fs");
const path = require("path");
const OSS = require("ali-oss");
const multer = require("multer");
const fetch = require("node-fetch");
const cors = require("cors");
const app = express();

app.use(cors());
app.use(express.json());

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = "uploads/";
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir);
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(
      null,
      file.fieldname + "-" + uniqueSuffix + path.extname(file.originalname)
    );
  },
});

const upload = multer({
  storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 限制10MB
  },
});

// 配置 OSS 客户端
const client = new OSS({
  region: "oss-cn-beijing", // 您 Bucket 所在的地域
  accessKeyId: "LTAI5t7EX6ki2crvDwzAhcEn",
  accessKeySecret: "PvsHZXCAJLyn0NMOvNurICrjOGFCEk",
  bucket: "ceshigpx",
});

/**
 * 上传文件到OSS
 * @param {string} objectName OSS存储的文件名
 * @param {string} filePath 本地文件路径
 */
async function uploadFile(objectName, filePath) {
  try {
    const result = await client.put(objectName, filePath);
    return result;
  } catch (err) {
    throw err;
  }
}

// 文件上传/修改接口
app.post("/upload", upload.single("file"), async (req, res) => {
  try {
    const checked = req.body.checked;
    // 获取元数据
    const { originalname, mimetype, size } = req.file;
    // 使用示例
    const { url } = await uploadFile("contentImage.jpg", req.file.path);
    res.json({ value: url, success: true });
  } catch (error) {
    console.error("文件上传错误:", error);

    res.status(500).json({
      error: "文件处理失败",
      message: error.message,
    });
  }
});

app.post('/api/process-image', upload.single('file'), async (req, res) => {
  try {
    // 获取所有参数
    const {
      modelId,
      description,
      poseFreedom,
      skinDetail,
      composition,
      generateCount,
      locationId,
      fileName
    } = req.body

    // 1. 上传文件到OSS
    const objectName = `uploads/${Date.now()}${path.extname(req.file.originalname)}`
    const { url: imageUrl } = await uploadFile(objectName, req.file.path)

    // 2. 调用WeShop API创建任务
    const taskResponse = await fetch('https://openapi.weshop.com/openapi/v1/agent/task/create', {
      method: 'POST',
      headers: {
        'Authorization': 'gBLoiveusjoTgEH16DBo5iUQFnOdAwcH',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        initParams: {
          taskName: fileName.slice(0, 20),
          originalImage: imageUrl
        },
        agentName: 'aimodel',
        agentVersion: 'v1.0'
      })
    })

    if (!taskResponse.ok) {
      throw new Error('创建任务失败')
    }

    const { data: { taskId } } = await taskResponse.json()
    const params = {
          pose: "originalImagePose",
          generatedContent: composition === '参考原图' ? "referToOrigin" : "referToScene",
          maskType: "autoApparelSegment",
          fashionModelId: Number(modelId),
          batchCount: 1,
          locationId:Number(locationId)
        }
    // 3. 执行任务
    const executeResponse = await fetch('https://openapi.weshop.com/openapi/v1/agent/task/execute', {
      method: 'POST',
      headers: {
        'Authorization': 'gBLoiveusjoTgEH16DBo5iUQFnOdAwcH',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        taskId,
        params: params,
        agentName: 'aimodel',
        agentVersion: 'v1.0'
      })
    })

    if (!executeResponse.ok) {
      throw new Error('执行任务失败')
    }
    console.log('taskId', taskId,params);


    const { data: { executionId } } = await executeResponse.json()
    // 4. 轮询结果
    let results
    let attempts = 0
    const maxAttempts = 500 // 最大尝试次数(约60秒超时)
    
    while (attempts < maxAttempts) {
      attempts++
      await new Promise(resolve => setTimeout(resolve, 20000))
      
      const queryResponse = await fetch('https://openapi.weshop.com/openapi/v1/agent/task/query', {
        method: 'POST',
        headers: {
          'Authorization': 'gBLoiveusjoTgEH16DBo5iUQFnOdAwcH',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ executionId })
      })

      if (!queryResponse.ok) {
        throw new Error('查询任务状态失败')
      }

      const { data: { executions } } = await queryResponse.json()
      
      const execution = executions[0]
      console.log('executions',execution);

      if (execution.status === 'Success') {
        results = execution.result
        console.log('results',execution.result);
        break
      }
    }
    
    if (!results) {
      throw new Error('任务处理超时')
    }

    // 返回处理结果
    res.json({
      success: true,
      imageUrl: results[0].image,
      taskId,
      executionId
    })

  } catch (error) {
    console.error('处理图片失败:', error)
    res.status(500).json({
      success: false,
      message: error.message
    })
  }
})

app.listen(3000, () => {
  console.log("服务器运行在 http://localhost:3000");
});
